﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace SummerTraining
{
    class Library
    {
        public static List<Book> BOOKS = new List<Book>();

        static Library()
        {
            Console.WriteLine("hello");
            Book b = new Book();
            b.Title = "The world is flat";
            Book b2 = new Book();
            b2.Title = "War and peace";
            Book b3 = new Book();
            b3.Title = "Rebecca";
            BOOKS.Add(b);
            BOOKS.Add(b2);
            BOOKS.Add(b3);
        }

        public event LibraryEventHandler BeforeBorrow;
        public event LibraryEventHandler OnReturn;

        public void Borrow(Book b, Reader r)
        {
            //BeforeBorrow();

            //往图书列表中找到一本书，把他的状态置为借出

            //AfterBorrow();

            LibraryEventArgs args = null;

            if (BeforeBorrow != null)
            {
                args = new LibraryEventArgs();
                args.Reader = r;
                args.Book = b;
                BeforeBorrow(this, args);
            }
            if (args == null || args.Cancle == false)
            {
                Book currBook = BOOKS.Find(book =>
                {
                    return book.Title == b.Title;
                });
                if (currBook != null)
                {
                    currBook.Reader = r;
                    currBook.Borrowed = true;
                    currBook.BorrowTime = DateTime.Now;
                }
            }
        }

        public void Return(Book b)
        {
            if (OnReturn != null)
            {
                OnReturn(this, null);
            }
            Book currBook = BOOKS.Find(book =>
            {
                return book.Title == b.Title;
            });

            if (currBook != null)
            {
                currBook.Borrowed = false;
            }
        }
    }

    class Book
    {
        public string Title
        {
            get;
            set;
        }
        public bool Borrowed
        {
            get;
            set;
        }
        public Reader Reader
        {
            get;
            set;
        }
        public DateTime BorrowTime
        {
            get;
            set;
        }
    }

    class Reader
    {
        public string Name
        {
            get;
            set;
        }
    }

    class LibraryEventArgs : EventArgs
    {
        public Book Book
        {
            get;
            set;
        }
        public Reader Reader
        {
            get;
            set;
        }
        public bool Cancle
        { 
            get; 
            set; 
        }
    }

    delegate void LibraryEventHandler(Library lib, LibraryEventArgs args);
}
